<template>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
    >
        <commentItem
        v-for="(item,index) in list"
        :key="index"
        @replyClick="$emit('replyClick',$event)"
        :comment="item"></commentItem>
    </van-list>
</template>
<script>
import { getCommentList } from '@/api/comment'
import commentItem from './comment-item'
export default {
  name: 'CommentList',
  components: {
    commentItem
  },
  props: {
    source: {
      type: [Number, String, Object],
      required: true
    },
    // 接收父组件传来的list  变量提升
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: 'a',
      validator(val) {
        return ['a', 'c'].includes(val)
      }
    }
  },
  data() {
    return {
      // list: [], // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束\
      offset: null,
      limit: 10,
      error: false
    }
  },

  methods: {
    async onLoad() {
      try {
        const { data } = await getCommentList({
          type: this.type,
          source: this.source.toString(),
          offset: this.offset,
          limit: this.limit
        })
        console.log(data)
        const { results } = data.data
        this.list.push(...results)
        this.loading = false
        if (results.length) {
          this.offset = data.data.last_id
        } else {
          this.finished = true
        }
      } catch (error) {
        this.loading = false
        this.error = true
        this.$toast('获取评论回复数据失败！')
      }
    }
  }
}
</script>
